import {_filename,byFile} from '../utils/tool.js';

let filename=_filename(import.meta.url);

let shortname=byFile(filename);

let goods=[
    {
        id:1,
        filename:"乐事薯片",
        year:2
    },
    {
        id:2,
        filename:"八宝粥",
        year:10
    },
    {
        id:3,
        filename:"干货",
        year:18
    },
    {
        id:4,
        filename:"文具",
        year:8
    },
    {
        id:5,
        filename:"水果",
        year:0.2
    },
]

//http://localhost:8080/goods

async function fn_getAll(ctx){
    ctx.body={
        code:1000,
        data:goods,
        msg:'获取所有商品成功'
    }
}

async function fn_getById(ctx){
    let id=ctx.params.id*1 || 0;
    console.log(id);
    let arr=films.filter(item=>{
        return item.id===id;
    });
    let res={
        code:1000,
        data:arr[0],
        msg:`获取指定${id}的商品名称成功`
    }
    ctx.body=res;
}

async function post(ctx){
    let obj=ctx.request.body;
    let lastid=goods[goods.length];
    obj['id']=lastid;
    goods.push(obj);
    ctx.body=obj;
};

async function put(ctx){
    let id=ctx.params.id *1 || 0;
    let reqparm=ctx.request.body;
    let arr=goods.filter(item=>{
        return item.id===id;
    });
    if(arr.length>0){
        let obj=arr[0];
        obj.filename=reqparm.filename;
        obj.year=reqparm.year;
        ctx.body={
            code:1000,
            msg:'修改成功'
        }
    }else{
        ctx.body={
            code:4000,
            msg:`没有找到ID为${id}的商品，请重试`
        }
    }
}

async function del(ctx){
    let id=ctx.params.id;
}

let obj=[];

obj[`get /${shortname}`]=fn_getAll;
obj[`get /${shortname}`]=fn_getById;
obj[`get /${shortname}`]=post;
obj[`get /${shortname}`]=put;
obj[`get /${shortname}`]=del;

export default obj;